//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-present, Egret Technology.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends eui.UILayer {


    protected createChildren(): void {
        super.createChildren();

        egret.lifecycle.addLifecycleListener((context) => {
            // custom lifecycle plugin
        })

        egret.lifecycle.onPause = () => {
            egret.ticker.pause();
        }

        egret.lifecycle.onResume = () => {
            egret.ticker.resume();
        }

        //inject the custom material parser
        //注入自定义的素材解析器
        let assetAdapter = new AssetAdapter();
        egret.registerImplementation("eui.IAssetAdapter", assetAdapter);
        egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());


        this.runGame().catch(e => {
            console.log(e);
        })
    }

    private async runGame() {
        await this.loadResource()
        this.createGameScene();
        const result = await RES.getResAsync("description_json")
        // this.startAnimation(result);
        await platform.login();
        const userInfo = await platform.getUserInfo();
        console.log(userInfo);

    }

    private async loadResource() {
        try {
            const loadingView = new LoadingUI();
            this.stage.addChild(loadingView);
            await RES.loadConfig("resource/default.res.json", "resource/");
            await this.loadTheme();
            await RES.loadGroup("preload", 0, loadingView);
            this.stage.removeChild(loadingView);
        }
        catch (e) {
            console.error(e);
        }
    }

    private loadTheme() {
        return new Promise((resolve, reject) => {
            // load skin theme configuration file, you can manually modify the file. And replace the default skin.
            //加载皮肤主题配置文件,可以手动修改这个文件。替换默认皮肤。
            let theme = new eui.Theme("resource/default.thm.json", this.stage);
            theme.addEventListener(eui.UIEvent.COMPLETE, () => {
                resolve();
            }, this);

        })
    }

    private textfield: egret.TextField;
    /**
     * 创建场景界面
     * Create scene interface
     */
    protected createGameScene(): void {

        GameData.stageWidth = this.stage.stageWidth;
        GameData.stageHeight = this.stage.stageHeight;
        GameData.GameStage = this.stage;

        var stageWidth:number = this.stage.stageWidth;
        var stageHeight:number = this.stage.stageHeight;

        var bm = this.createBitmapByName('man_png');
        bm.width = bm.height = 100;
        bm.x = 0;
        bm.y = stageHeight-500;
        this.addChild(bm);

        // var map:GameMap = new GameMap();
        // map.x = map.y = 0;
        // this.addChild(map);
        // map.init(1);
        // this.createMan(60,60,100,100,'man_png',map.p2World);

        var left_btn:egret.DisplayObject = this.createBitmapByName('zfx_png');
        var right_btn:egret.DisplayObject = this.createBitmapByName('zfx_png');
        var up_btn:egret.DisplayObject = this.createBitmapByName('zfx_png');

        left_btn.x = 80;
        left_btn.y = stageHeight - 100;
        up_btn.width = up_btn.height = right_btn.width = right_btn.height = left_btn.width = left_btn.height = 80;
        left_btn.touchEnabled = right_btn.touchEnabled = up_btn.touchEnabled = true;
        right_btn.x = 250;
        right_btn.y = stageHeight - 100;

        up_btn.x = 700;
        up_btn.y = stageHeight - 100;
        
        this.addChild(left_btn);
        this.addChild(right_btn);
        this.addChild(up_btn);
        
        left_btn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.left_click, this);
        right_btn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.right_click, this);
        up_btn.addEventListener(egret.TouchEvent.TOUCH_BEGIN, this.up_click, this);

        //  BeginLogic.getInstance().openUI(this,new BeginUI());
         GameLogic.getInstance().openUI(this,new GameUI());
    }

    /**
     * 点击按钮
     * Click the button
     */
    private onButtonClick(e: egret.TouchEvent) {
        let panel = new eui.Panel();
        panel.title = "Title";
        panel.horizontalCenter = 0;
        panel.verticalCenter = 0;
        this.addChild(panel);
    }

    private left_click(e:TouchEvent){
        this.manBody.velocity[0] = -3;
        console.log('left');
    }

    private right_click(e:TouchEvent){
        this.manBody.velocity[0] = 3;
        console.log('right');
    }

    private up_click(e:TouchEvent){
        this.manBody.velocity[1] = 10;
        console.log('up');
    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     */
    private createBitmapByName(name: string): egret.Bitmap {
        var result: egret.Bitmap = new egret.Bitmap();
        var texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }

    private manBody:p2.Body;
    private createMan(w:number,h:number,x:number,y:number,resid:string,world: p2.World){
        var factorc = 0.02;
        var factorx = 50;
        var stageHeight:number = this.stage.stageHeight;//egret.MainContext.instance.stage.stageHeight;

        var boxShape: p2.Shape = new p2.Box({width: w*factorc, height: h*factorc});
        var boxBody: p2.Body = new p2.Body({ mass: 30, position: [(x+w*0.5)*factorc, (stageHeight - (y+h*0.5))*factorc]});
        boxBody.addShape(boxShape);
        world.addBody(boxBody);
        var downDisplay:egret.DisplayObject = this.createBitmapByName(resid);
        boxBody.fixedRotation = true;

        downDisplay.width = w;
        downDisplay.height = h;

        downDisplay.x = boxBody.position[0] * factorx;
        downDisplay.y = stageHeight - boxBody.position[1] * factorx;

        downDisplay.anchorOffsetX = downDisplay.width / 2;
        downDisplay.anchorOffsetY = downDisplay.height / 2;
        console.log(downDisplay.x,downDisplay.y);
        this.addChild(downDisplay);
        boxBody.displays = [downDisplay];

        this.manBody = boxBody;
    }
}
